import router from '../router'
import ViewUI from 'view-design'


const instance = axios.create({
  baseURL: 'http://localhost:8088/',
  timeout: 20000
})

instance.interceptors.request.use(
  config => {
    ViewUI.LoadingBar.start()
    if (localStorage.token) {
      config.headers.token = localStorage.token;
    }
    return config;
  }, err => {
    console.log(err)
    router.replace('/error')
    return Promise.reject(error)
  }
) 

instance.interceptors.response.use(
  res => {
    switch (res.data.statusCode) {
      case 500:
        ViewUI.LoadingBar.error()
        break
      case 404:
        ViewUI.LoadingBar.error()
        router.replace('/error')
        break
      case 401:
        ViewUI.LoadingBar.finish()
        router.replace('/error')
        break
      default:
        ViewUI.LoadingBar.finish()
        break
    }
    return res
  }, async error => {
    ViewUI.LoadingBar.error()
    console.dir(error)
    router.replace('/error')
    return Promise.reject(error)
  }
)

export default instance